package com.delayqueue.core.permanent;

import com.delayqueue.common.task.Task;
import com.delayqueue.core.common.FileUtil;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.HashSet;

@Component
@Getter
public class PermanentFile {

    @Autowired
    private PermanentConfig permanentConfig;

    //持久化文件
    private File taskDataFile;
    private File completedDataFile;
    //clean期间临时写入的文件路径
    private File taskTempFile;
    private File completedTempFile;


    @PostConstruct
    private void init() {
        if (permanentConfig.getEnabled()) {
            taskDataFile = new File(makeFilePath("task.data"));
            taskTempFile = new File(makeFilePath("task.tmp"));
            completedDataFile = new File(makeFilePath("completed.data"));
            completedTempFile = new File(makeFilePath("completed.tmp"));
        }
    }

    public void clearDataFile() {
        FileUtil.clearFile(taskDataFile);
        FileUtil.clearFile(completedDataFile);
    }

    public void clearCompletedDataFile() {
        FileUtil.clearFile(completedDataFile);
    }

    public void deleteTempFile() {
        if (taskTempFile != null) {
            taskTempFile.delete();
        }
        if (completedTempFile != null) {
            completedTempFile.delete();
        }
    }


    private String makeFilePath(String fileName) {
        return permanentConfig.getDataDir() + "/" + fileName;
    }

    public HashSet<Task> loadTaskList() {
        return FileUtil.loadTaskListFromFile(taskDataFile);
    }

    public HashSet<String> loadCompletedCodeList() {
        return FileUtil.loadContentFromFile(completedDataFile);
    }
}
